package com._21cn.cms.article.web.controller;

import com._21cn.cms.article.Constants;
import com._21cn.cms.article.entity.*;
import com._21cn.cms.article.entity.vo.ArticlePushResult;
import com._21cn.cms.article.entity.vo.SearchArticle;
import com._21cn.cms.article.service.ArticleService;
import com._21cn.cms.article.service.ColumnArticleService;
import com._21cn.cms.article.service.RegionArticleService;
import com._21cn.cms.article.utils.ArticleHelper;
import com._21cn.cms.article.utils.ArticlePushHelper;
import com._21cn.cms.article.utils.PublishHelper;
import com._21cn.cms.common.FormSelector;
import com._21cn.cms.site.entity.Channel;
import com._21cn.cms.site.entity.Column;
import com._21cn.cms.site.service.ChannelService;
import com._21cn.cms.site.service.ColumnService;
import com._21cn.framework.base.controller.BaseController;
import com._21cn.framework.flip.PageList;
import com._21cn.framework.http.HttpRequestInfo;
import com._21cn.framework.utils.CollectionUtil;
import com._21cn.framework.utils.DateUtil;
import com._21cn.framework.utils.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Controller
@RequestMapping("/admin/article/article")
public class ArticleController extends BaseController{

	private static String listView = "/admin/article/article/list";
    private static String showView = "/admin/article/article/show";
    private static String jsonView = "/admin/article/article/json";
    private static String formView = "/admin/article/article/form";
    private static String redirectListView = "redirect:/admin/article/article/list.do";

    private Map<String, String> propertyTitleMap = null;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ColumnArticleService columnArticleService;

    @Autowired
    private RegionArticleService regionArticleService;

    @Autowired
    private ColumnService columnService;

    @Autowired
    private ChannelService channelService;

    @Autowired(required = false)
    private ArticleHelper articleHelper;

    @Autowired(required=false)
    private PublishHelper publishHelper;

    @Autowired(required = false)
    private ArticlePushHelper articlePushHelper;
	
	@Autowired(required = false)
    @Qualifier("articleValidator")
    private Validator articleValidator;

    @RequestMapping("/list")
    public String listArticle(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", listView);
        setRequestModelMap( request, model, true );
        model.addAttribute( "publishStatusMap", FormSelector.getPublishStatusMap() );
        return view;
    }

    @RequestMapping("/search")
    public String searchArticle(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", jsonView );
        setRequestModelMap( request, model, true );
        PageList<SearchArticle> result = getPageList( model );
        model.addAttribute( "objListJson" , com.alibaba.fastjson.JSON.toJSONString(result, SerializerFeature.WriteDateUseDateFormat) );
        return view;
    }

    @RequestMapping("/show")
    public String showArticle(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", showView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        if( id > 0 ){
            Article article = articleService.getById( id );
            if( article == null ){
                model.put( "error.param.wrong", "无效参数" );
            }
            model.addAttribute( "article", article );
        }
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/edit")
    public String editArticle(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        String view = reqInfo.getParameter( "view", formView );
        Integer id = reqInfo.getIntParameter( "id", -1 );
        Article article = new Article();
        if( id > 0 ){
            article = articleService.getById(id);
            if( article == null ){
                model.put( "error.param.wrong", "无效参数" );
            }else {
                articleHelper.regulateColumns(article);
                articleHelper.regulateRegions(article);
                //图片列表
                List<ArticlePicture> articlePictureList = article.getArticlePictureList();
                List<ArticleThumbPicture> articleThumbPicList = article.getArticleThumbPictureList();
                List<String> picUrls = new ArrayList<String>();
                for (ArticlePicture articlePicture : articlePictureList) {
                    picUrls.add(articlePicture.getPicUrl());
                }
                List<String> picUrlList = new ArrayList<String>();
                for (ArticleThumbPicture articleThumbPicture : articleThumbPicList) {
                    picUrlList.add(articleThumbPicture.getPicUrl());
                    if (picUrls.contains(articleThumbPicture.getPicUrl())) {
                        continue;
                    }
                    ArticlePicture articlePicture = new ArticlePicture();
                    articlePicture.setPicUrl(articleThumbPicture.getPicUrl());
                    articlePictureList.add(articlePicture);
                }
                for (ArticlePicture articlePicture : articlePictureList) {
                    if (articleThumbPicList.size() > 0 && picUrlList.contains(articlePicture.getPicUrl())) {
                        articlePicture.setStatus(2); // 是否checked
                    }
                }
                model.addAttribute("articlePictureList", articlePictureList);
            }
        }
        model.addAttribute( "article", article );
        setRequestModelMap(request, model);
        return view;
    }
	
	@RequestMapping("/save")
    public String saveArticle(HttpServletRequest request, ModelMap model) {
	    try{
            HttpRequestInfo reqInfo = new HttpRequestInfo(request);
            Integer id = reqInfo.getIntParameter( "id", -1 );
            String[] imgUrls = request.getParameterValues("thumbPicUrl");
            Integer columnId = reqInfo.getIntParameter("mainColumnId", 0);
            String relateColumnIds = reqInfo.getParameter("relateColumnIds", "");
            String regionIds = reqInfo.getParameter("regionIds", "");
            String topTimeStr = reqInfo.getParameter("topTimeStr","");
            Integer topTime = 0;
            if(!StringUtil.isEmpty(topTimeStr)){
                Date topDate =  DateUtil.parseDate(topTimeStr , "yyyy-MM-dd HH:mm:ss");
                topTime = DateUtil.get10TimeStamp(topDate);
            }else {
                topTime = DateUtil.get10TimeStamp(new Date());
            }


            Set<Integer> newRelateColumnIdSet = StringUtil.str2IntSet(relateColumnIds);

            if(newRelateColumnIdSet.contains(columnId)){
                model.put( "error.param.wrong", "主（从）栏目重复推送" );
                return formView;
            }

            Article article = new Article();
            if( id>0 ){                                         //更新
                article = articleService.getById( id );
                if( bind( request, article, model,  articleValidator).hasErrors() ){
                    return formView;
                }

                if( article!=null ){
                    formatThumbPics(article, imgUrls);
                    article.setPublishStatus( Constants.PUBLISH_STATUS_DONE);
                    articleHelper.regulateColumns(article);     //获取旧主从栏目信息
                    articleHelper.regulateRegions(article);     //获取旧区块信息
                    int oldMainColumnId = article.getMainColumnId();
                    String oldRelateColumnIds = article.getRelateColumnIds();
                    Set<Integer> oldRelateColumnIdSet = StringUtil.str2IntSet(oldRelateColumnIds);
                    article.setTopTime(topTime);

                    if( columnId.equals(oldMainColumnId)
                            && CollectionUtil.equals(oldRelateColumnIdSet, newRelateColumnIdSet)){  //主栏目和从栏目不变
                        articleHelper.regulate4Save(article);
                        articleService.update( article );
                        articlePushHelper.updateMainColumnArticle(article, columnId, true);
                        articlePushHelper.updateRelateColumnArticle(article, relateColumnIds, true);
                    }else {
                        if( !columnId.equals(oldMainColumnId) ){      //主栏目改变
                            article.setColumnId(columnId);
                        }
                        articleHelper.regulate4Save(article);
                        articleService.update( article );
                        articlePushHelper.updateMainColumnArticle(article, columnId, true);
                        articlePushHelper.updateRelateColumnArticle(article, relateColumnIds, true);
                    }
                    articlePushHelper.updateRegionArticles(article, regionIds, true);
                }else{
                    model.put( "error.param.wrong", "文章为null" );
                    return formView;
                }
            }else{                                              //添加
                if( bind( request, article, model,  articleValidator).hasErrors() ){
                    return formView;
                }
                article.setTopTime(topTime);
                article.setColumnId(columnId);
                formatThumbPics(article, imgUrls);
                article.setPublishStatus( reqInfo.getIntParameter("publishStatus", Constants.PUBLISH_STATUS_DONE) );
                articleHelper.regulate4Save(article);
                articleService.insert( article );
                articlePushHelper.insertMainColumnArticle(article, columnId, true);
                articlePushHelper.insertRelateColumnArticle(article, relateColumnIds, true);
                articlePushHelper.insertRegionArticles(article, regionIds, true);
            }
            model.clear();
            return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
        }catch (Exception e){
            model.put( "error.param.wrong", "系统异常:"+e.getMessage() );
            return formView;
        }
    }
	
	@RequestMapping("/updateStatus")
    public String updateArticleStatus(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Integer status = reqInfo.getIntParameter( "status", -1 );
        if( status < 0 ){
            model.clear();
            return redirectListView+ "?" + reqInfo.getParameter( "queryParam", "" );
        }
        setRequestModelMap(request, model);
        String objectIds = getGetObjectIds( reqInfo, model );
        if( objectIds.length() > 0 ){
            articleService.update( model );
        }
        model.clear();
        return redirectListView + "?" + reqInfo.getParameter( "queryParam", "" );
    }

    @RequestMapping({"/withdraw"})
    @ResponseBody
    public String deleteArticle(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        String idAndslave = reqInfo.getParameter("idAndslave", "");
        Set articleIdSet = new HashSet();
        Set<Integer> regionIdSet = new HashSet<Integer>();
        if (!StringUtil.isEmpty(idAndslave)) {
            String[] idAndslaveAry = idAndslave.split(",");
            Map<Integer, Integer> slaveMap = new HashMap();
            Map<Integer, Integer> masterMap = new HashMap();
            String[] tmp;
            for (String ary : idAndslaveAry) {
                tmp = ary.split("_");
                int articleId = Integer.parseInt(tmp[0].trim());
                int slaveFlag = tmp[1].trim().equals("1") ? 1 : 0;
                int columnId = Integer.parseInt(tmp[2].trim());
                if (slaveFlag == Constants.PUBLISH_COLUMN_MASTER)
                    masterMap.put(articleId, columnId);
                else if (slaveFlag == Constants.PUBLISH_COLUMN_SLAVE) {
                    slaveMap.put(articleId, columnId);
                }
                articleIdSet.add(articleId);
            }

            if (articleIdSet.size() > 0) {
                Map<String, Object> params = new HashMap();
                List<Integer> inArticleIdList = new ArrayList(articleIdSet);
                ((Map)params).put("inArticleIdList", inArticleIdList);
                List<RegionArticle> raList = regionArticleService.getList((Map)params, 1, 100, false);
                if (raList.size() > 0) {
                    ((Map)params).put("publishStatus", Integer.valueOf(4));
                    regionArticleService.update((Map)params);
                    for (RegionArticle regionArticle : raList) {
                        regionIdSet.add(regionArticle.getRegionId());
                    }
                    for (Integer regionId : regionIdSet) {
                        publishHelper.addRegionTask(regionId.intValue());
                    }
                }
            }

            for(Map.Entry<Integer, Integer> entry : slaveMap.entrySet()){
                if (masterMap.containsKey(entry.getKey())) {
                    slaveMap.remove(entry.getKey());
                }
            }

            for(Map.Entry<Integer, Integer> entry : masterMap.entrySet()){
                int articleId = ((Integer)entry.getKey()).intValue();
                Article article = this.articleService.getById(Integer.valueOf(articleId));
                if (article != null)
                {
                    Map params = new HashMap();
                    params.put("eqArticleId", articleId);
                    params.put("publishStatus",Constants.PUBLISH_STATUS_CANCEL);
                    params.put("modifyTime", new Date());
                    this.columnArticleService.update(params);

                    params.clear();
                    params.put("eqId", article.getId());
                    params.put("publishStatus", Constants.PUBLISH_STATUS_CANCEL);
                    params.put("modifyTime", new Date());
                    this.articleService.update(params);

                    article.setPublishStatus(Constants.PUBLISH_STATUS_CANCEL);
                    this.publishHelper.publishArticle(article);
                }
            }

            for (Map.Entry<Integer, Integer> entry : slaveMap.entrySet()){
                Integer articleId = (Integer)entry.getKey();
                Integer columnId = (Integer)entry.getValue();

                Map params = new HashMap();
                params.put("eqArticleId", articleId);
                params.put("eqColumnId", columnId);
                params.put("publishStatus", Integer.valueOf(4));
                params.put("modifyTime", new Date());
                this.columnArticleService.update(params);
            }
        }
        Map result = new HashMap();
        result.put("succs", "成功撤稿");
        return JSON.toJSONString(result);
    }

    @RequestMapping({"/rePublish"})
    @ResponseBody
    public String rePublish(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        setRequestModelMap(request, model);
        String ids = reqInfo.getParameter("ids", "");
        if (!StringUtil.isEmpty(ids)) {
            Set<Integer> idSet = StringUtil.str2IntSet(ids);
            for (Integer id : idSet) {
                ColumnArticle columnArticle = columnArticleService.getById(id);
                Integer articleId = columnArticle.getArticleId();
                Article article = articleService.getById(articleId);
                columnArticle.setPublishStatus(Constants.PUBLISH_STATUS_DONE);
                article.setPublishStatus(Constants.PUBLISH_STATUS_DONE);
                this.columnArticleService.update(columnArticle);
                this.articleService.update(article);
                this.publishHelper.publishArticle(article);
            }
        }
        Map result = new HashMap();
        result.put("succs", "完成发布");
        return JSON.toJSONString(result);
    }

    @RequestMapping("/push")
    @ResponseBody
    public String pushArticle(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
        HttpRequestInfo reqInfo = new HttpRequestInfo(request);
        Map<String,List<ArticlePushResult>> result = new HashMap<String,List<ArticlePushResult>>();

        String articleIds = reqInfo.getParameter("articleIds", null);
        String targetIds = reqInfo.getParameter("targetIds", null);
        String type = reqInfo.getParameter("type", "column");
        List<ArticlePushResult> succs = new ArrayList<ArticlePushResult>();
        if(!StringUtil.isEmpty(articleIds) && !StringUtil.isEmpty(targetIds)){
            Set<Integer> articleIdSet = StringUtil.str2IntSet(articleIds);
            for(Integer articleId: articleIdSet){
                Article article = articleService.getById(articleId);
                if(article != null){
                    if(type.equals("column")){
                        succs = articlePushHelper.insertRelateColumnArticle(article, targetIds, true);
                    }else if(type.equals("region")){
                        succs = articlePushHelper.insertRegionArticles(article, targetIds, true);
                    }
                }
            }
        }
        result.put("succs", succs);
        return com.alibaba.fastjson.JSON.toJSONString(result);
    }
	
	private PageList<SearchArticle> getPageList(ModelMap model) {
        if (model.containsKey("likeName"))
            model.put("likeName",model.get("likeName").toString().toLowerCase());
            model.addAttribute("orderByClause", "article.ID desc");

        PageList<SearchArticle> articleList = articleService.getSearchArticleList( model, Integer.parseInt(model.get("pageNo").toString()), Integer.parseInt(model.get("pageSize").toString()), true );
        for( SearchArticle searchArticle : articleList ){
            Channel channel = channelService.getById(searchArticle.getChannelId());
            Column column = columnService.getById(searchArticle.getColumnId());
            searchArticle.setMainChannel(channel.getName());
            searchArticle.setMainColumn(column.getName());
        }
        model.addAttribute( "articleList", articleList);
        model.addAttribute( "objList", articleList);
        model.addAttribute( "pageTurn", articleList.getPageTurn());
        model.addAttribute( "titleMap", getPropertyTitleMap() );
        return articleList;
    }

    private Article formatThumbPics(Article article, String[] imgUrls){
        if (imgUrls != null && imgUrls.length > 0) {        //设置缩略图
            List<String> thumbUrlList = new ArrayList<String>();
            for (String imgUrl: imgUrls) {
                imgUrl = imgUrl.replace("/s/", "/o/");
                thumbUrlList.add(imgUrl);
            }
            Map<String, Object> resultMap = new HashMap<String, Object>();
            resultMap.put("list", thumbUrlList);
            String json = JSONObject.toJSONString(resultMap);
            article.setThumbPicUrlListStr(json);
        }
        return article;
    }

    private Map<String, String> getPropertyTitleMap() {
        if( propertyTitleMap == null ){
			propertyTitleMap = new HashMap<String,String>();
			propertyTitleMap.put( "id", "id" );
			propertyTitleMap.put( "siteId", "siteId" );
			propertyTitleMap.put( "title", "title" );
			propertyTitleMap.put( "titleShort", "titleShort" );
			propertyTitleMap.put( "summary", "summary" );
			propertyTitleMap.put( "keyword", "keyword" );
			propertyTitleMap.put( "sourceName", "sourceName" );
			propertyTitleMap.put( "author", "author" );
			propertyTitleMap.put( "firstPicUrl", "firstPicUrl" );
			propertyTitleMap.put( "articleUrl", "articleUrl" );
			propertyTitleMap.put( "articleType", "articleType" );
			propertyTitleMap.put( "publishTime", "publishTime" );
			propertyTitleMap.put( "publishStatus", "publishStatus" );
			propertyTitleMap.put( "createUserId", "createUserId" );
			propertyTitleMap.put( "createTime", "createTime" );
			propertyTitleMap.put( "modifyUserId", "modifyUserId" );
			propertyTitleMap.put( "modifyTime", "modifyTime" );
			propertyTitleMap.put( "clickNum", "clickNum" );
			propertyTitleMap.put( "summaryFlag", "summaryFlag" );
			propertyTitleMap.put( "reviewFlag", "reviewFlag" );
			propertyTitleMap.put( "picFlag", "picFlag" );
        }
        return propertyTitleMap;
    }
}
